package com.zhai.trigger.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zhai.domain.activity.service.IRaffleActivitySkuStockService;
import com.zhai.types.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Description: 活动sku库存为0时监听处理
 * @ClassName: ActivitySkuStockZeroCustomer
 * @Author: zhaiyongxin
 * @Date: 2025/2/25 14:11
 * @Version: 1.0
 */
@Component
@Slf4j
public class ActivitySkuStockZeroCustomer {

    @Value("${spring.rabbitmq.topic.activity_sku_stock_zero}")
    private String topic;
    @Resource
    private IRaffleActivitySkuStockService skuStock;

    @RabbitListener(queuesToDeclare = @Queue(value = "activity_sku_stock_zero"))
    public void listener(String message){
        try {
            log.info("监听活动sku库存消耗为0的消息 topic:{} message:{}",topic, message);
            // 1.获取队列数据
            BaseEvent.EventMessage<Long> eventMessage = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<Long>>(){}.getType());
            Long sku = eventMessage.getData();
            // 2.更新数据库数量为0
            skuStock.clearActivitySkuStock(sku);
            // 3.清空redis队列及锁
            skuStock.clearQueueValue(sku);
        } catch (Exception e) {
            log.error("监听活动sku库存消耗为0消息，消费失败 topic: {} message: {}", topic, message);
            throw e;
        }
    }
}
